package com.yunxi.service.dubboService.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.github.pagehelper.PageInfo;
import com.yunxi.baseDataToHub.pojo.sap.VehicleBatchOrderModifyVO;
import com.yunxi.baseDataToHub.pojo.sap.VehicleBatchOrderVO;
import com.yunxi.baseDataToHub.service.sap.SapDubboService;
import com.yunxi.bizToBaseData.pojo.VehiclePriceReqVO;
import com.yunxi.bizToBaseData.service.SToSVehiclePriceDubboService;
import com.yunxi.core.base.Constant;
import com.yunxi.core.enums.DMSEnumsEntity;
import com.yunxi.core.util.WgrDate;
import com.yunxi.core.web.ApiResult;
import com.yunxi.model.base.BaseApplyLevel;
import com.yunxi.model.order.OrderVehicle;
import com.yunxi.model.order.VehicleReturApply;
import com.yunxi.model.sto.StoStockInPlan;
import com.yunxi.model.stock.PartnerStockOut;
import com.yunxi.order.pojo.*;
import com.yunxi.order.service.VehicleReturApplyDubboService;
import com.yunxi.service.localService.*;
import com.yunxi.service.localService.sto.StoStockInPlanService;
import com.yunxi.sto.pojo.StoStockInPlanVO;
import com.yunxi.stock.pojo.PartnerStockOutReqVO;
import com.yunxi.stock.pojo.PartnerStockOutRespVO;
import com.yunxi.stock.pojo.PartnerStockOutSignInReqVO;
import org.dozer.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 渠道商退车申请审核业务
 */
public class VehicleReturApplyDubboServiceImpl implements VehicleReturApplyDubboService {

    private final Logger logger = LoggerFactory.getLogger(VehicleReturApplyDubboServiceImpl.class);

    @Autowired
    @Qualifier(value = "partnerStockOutServiceImpl")
    PartnerStockOutService partnerStockOutServiceImpl;

    @Autowired
    @Qualifier(value = "baseApplyLevelServiceImpl")
    BaseApplyLevelService baseApplyLevelServiceImpl;

    @Autowired
    SapDubboService sapDubboServiceImpl;

    @Autowired
    SToSVehiclePriceDubboService stoSVehiclePriceDubboServiceImpl;

    @Autowired
    private Mapper dozerMapper;

    @Autowired
    VehicleReturApplyService vehicleReturApplyServiceImpl;

    /**
     * 批售单子订单业务层
     */
    @Autowired
    @Qualifier(value = "orderVehicleServiceImpl")
    OrderVehicleService orderVehicleServiceImpl;

    @Autowired
    @Qualifier(value = "stoStockInPlanServiceImpl")
    StoStockInPlanService stoStockInPlanService;

    /**
     * 序列号生成器
     */
    @Autowired
    @Qualifier("codeCreateServiceImpl")
    CodeCreateService codeCreateServiceImpl;

    /**
     * 渠道商退车申请主数据查询
     * @param vo
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    @Transactional
    @LcnTransaction
    public PageInfo<VehicleReturApplyQueryRespVO> queryByList(VehicleReturApplyQueryReqVO vo,int pageNum,int pageSize) {
        return vehicleReturApplyServiceImpl.findListByVO(vo,pageNum,pageSize);
    }

    /**
     * 渠道商退车申请
     * @param vo
     * @return
     */
    @Override
    @Transactional
    @LcnTransaction
    public boolean applyReturVehicle(VehicleReturApplyReqVO vo) {
        if(vo == null){
            logger.info("VO对象为Null，参数非法，请核实！");
            throw new RuntimeException("VO对象为Null，参数非法，请核实！");
        }

        QueryWrapper qw = new QueryWrapper();
        qw.eq("ORDER_CAR_ID",vo.getOrderCarId());
        qw.notIn("CHECK_STATUS",Constant.PMS_ORDER_CANCEL_REASON_CHECK_STATUS_REJECT);
        VehicleReturApply tmp =  vehicleReturApplyServiceImpl.getOne(qw);
        if(tmp != null){
            logger.info("您的退车申请已提交，请勿重复申请！");
            throw new RuntimeException("您的退车申请已提交，请勿重复申请！");
        }

        VehicleReturApply vehicleReturApply = new VehicleReturApply();
        String vraCode = codeCreateServiceImpl.createCode("VRA", 4);
        vehicleReturApply.setVehicleReturId(vraCode);
        vehicleReturApply.setCreateBy(vo.getUserCode());
        vehicleReturApply.setCheckStatus(Constant.PMS_ORDER_CANCEL_REASON_CHECK_STATUS_WAIT_AUDIT);
        vehicleReturApply.setOneLevelCheckStatus(Constant.PMS_ORDER_CANCEL_REASON_CHECK_STATUS_WAIT_AUDIT);
        vehicleReturApply.setInfo(vo.getInfo());
        vehicleReturApply.setOrderCarId(vo.getOrderCarId());
        vehicleReturApply.setCurrentLevel(1);
        return vehicleReturApplyServiceImpl.save(vehicleReturApply);
    }

    /**
     * 审核
     * @param vo
     * @return
     */
    @Override
    @Transactional
    @LcnTransaction
    public boolean verify(VehicleReturApplyVerifyReqVO vo) {
        if(vo == null){
            logger.info("VO对象为Null，参数非法，请核实！");
            throw new RuntimeException("VO对象为Null，参数非法，请核实！");
        }
        QueryWrapper qwBaseApplyLevel = new QueryWrapper();
        qwBaseApplyLevel.eq("USER_CODE",vo.getUserCode());
        qwBaseApplyLevel.eq("BUS_ID",Constant.PMS_VERIFY_RETUR_VEHICLE);
        BaseApplyLevel baseApplyLevel = baseApplyLevelServiceImpl.getOne(qwBaseApplyLevel);


        QueryWrapper qwEntity = new QueryWrapper();
        qwEntity.eq("VEHICLE_RETUR_ID",vo.getVehicleReturId());
        VehicleReturApply entity = vehicleReturApplyServiceImpl.getOne(qwEntity);
        if(baseApplyLevel.getCurrentLevel() == 1){
            if(entity != null && entity.getOneLevelAuditBy() != null){
                 logger.info("您已经审核过了，无需重复审核！");
                 throw new RuntimeException("您已经审核过了，无需重复审核！");
            }
        }else if(baseApplyLevel.getCurrentLevel() == 2){
            if(entity != null && entity.getTwoLevelAuditBy() != null){
                logger.info("您已经审核过了，无需重复审核！");
                throw new RuntimeException("您已经审核过了，无需重复审核！");
            }
        }else if(baseApplyLevel.getCurrentLevel() == 3){
            if(entity != null && entity.getThreeLevelAuditBy() != null){
                logger.info("您已经审核过了，无需重复审核！");
                throw new RuntimeException("您已经审核过了，无需重复审核！");
            }
        }


        VehicleReturApply vehicleReturApply = new VehicleReturApply();
        QueryWrapper qw = new QueryWrapper();
        qw.eq("VEHICLE_RETUR_ID",vo.getVehicleReturId());

        if(baseApplyLevel.getCurrentLevel() == 1){ //一级审核
            vehicleReturApply.setOneLevelCheckStatus(vo.getCheckStatus());
            vehicleReturApply.setOneLevelAuditBy(vo.getUserCode());
            vehicleReturApply.setCurrentLevel(2);

        }else if(baseApplyLevel.getCurrentLevel() == 2){ //二级审核
            vehicleReturApply.setTwoLevelCheckStatus(vo.getCheckStatus());
            vehicleReturApply.setTwoLevelAuditBy(vo.getUserCode());
            vehicleReturApply.setCurrentLevel(3);

        }else if(baseApplyLevel.getCurrentLevel() == 3){ //三级审核
            vehicleReturApply.setThreeLevelCheckStatus(vo.getCheckStatus());
            vehicleReturApply.setThreeLevelAuditBy(vo.getUserCode());
            vehicleReturApply.setCurrentLevel(0);
        }

        //
        //表示三级审核中有一个驳回，整个单子就驳回了
        if(vo.getCheckStatus() == Constant.PMS_ORDER_CANCEL_REASON_CHECK_STATUS_REJECT){
            vehicleReturApply.setCheckStatus(Constant.PMS_ORDER_CANCEL_REASON_CHECK_STATUS_REJECT);
            vehicleReturApply.setCurrentLevel(0);
            OrderVehicle orderVehicle = new OrderVehicle();
            orderVehicle.setCheckStatus(Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_REJECT);

            QueryWrapper qwOrderVehicle = new QueryWrapper();
            qwOrderVehicle.eq("ORDER_CAR_ID",entity.getOrderCarId());

            orderVehicleServiceImpl.update(orderVehicle,qwOrderVehicle);
        }else if(baseApplyLevel.getCurrentLevel() == 3 && vo.getCheckStatus().intValue() == Constant.PMS_ORDER_CANCEL_REASON_CHECK_STATUS_CHECK_PASS.intValue()){
              //
              //表示第三级审核为审核通过
            vehicleReturApply.setCheckStatus(Constant.PMS_ORDER_CANCEL_REASON_CHECK_STATUS_CHECK_PASS);

            //
            //三级审核通过后，修改订单表状态为销售退车
            OrderVehicle orderVehicle = new OrderVehicle();
            orderVehicle.setCheckStatus(Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_RETURN_CAR);

            QueryWrapper qwOrderVehicle = new QueryWrapper();
            qwOrderVehicle.eq("ORDER_CAR_ID",entity.getOrderCarId());

            orderVehicleServiceImpl.update(orderVehicle,qwOrderVehicle);


            OrderVehicle getVinByOrderVehicle = orderVehicleServiceImpl.getOne(qwOrderVehicle);
            //
            //调用SAP退车
            callSapInvokVehicleBatchOrderByVin(getVinByOrderVehicle.getVin());
        }

        vehicleReturApply.setRejectInfo(vo.getRejectInfo());
        vehicleReturApplyServiceImpl.update(vehicleReturApply,qw);

        return true;
    }

    /**
     * 到批售单中查找当前VIN是否存在，如果存在表示已经配过车了
     * 如果不存在直接返回
     *
     * @param vin
     */
    public void callSapInvokVehicleBatchOrderByVin(String vin) {
        QueryWrapper qwByVin = new QueryWrapper();
        qwByVin.eq("VIN", vin);
        qwByVin.eq("CHECK_STATUS", Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_WAIT_PUT_IN_STORAGE);
        OrderVehicle orderVehicle = orderVehicleServiceImpl.getOne(qwByVin);
        if (orderVehicle == null) {
            return;
        }

        CallSapInvokVehicleBatchOrderReqVO callSapInvokVehicleBatchOrderReqVO = new CallSapInvokVehicleBatchOrderReqVO();
        callSapInvokVehicleBatchOrderReqVO.setOrderCarId(orderVehicle.getOrderCarId());
        callSapInvokVehicleBatchOrderReqVO.setOrderType("7"); //表示退货
        callSapInvokVehicleBatchOrderReqVO.setPartnerCode(orderVehicle.getPartnerCode());//客户编号
        callSapInvokVehicleBatchOrderReqVO.setOrgnize(Constant.ORGNIZE);//销售组织
        callSapInvokVehicleBatchOrderReqVO.setPayway(orderVehicle.getPayway());
        if ("Y".equals(orderVehicle.getIsPickup())) {
            //自提
            callSapInvokVehicleBatchOrderReqVO.setPickUp("02");
        } else if ("N".equals(orderVehicle.getIsPickup())) {
            //物流
            callSapInvokVehicleBatchOrderReqVO.setPickUp("03");
        }

        callSapInvokVehicleBatchOrderReqVO.setOrderDate(WgrDate.date2Str(orderVehicle.getCreateDate(), "yyyyMMdd"));
        callSapInvokVehicleBatchOrderReqVO.setCatalogCode(orderVehicle.getCatalogCode());
        callSapInvokVehicleBatchOrderReqVO.setVin(orderVehicle.getVin());
        callSapInvokVehicleBatchOrderReqVO.setNum("1");
        callSapInvokVehicleBatchOrderReqVO.setDispatchDate(WgrDate.date2Str(orderVehicle.getDispatchDate(), "yyyyMMdd"));
        callSapInvokVehicleBatchOrderReqVO.setAddr(orderVehicle.getAddr());
        callSapInvokVehicleBatchOrderReqVO.setCertAddr(orderVehicle.getAddr());

        String addr = orderVehicleServiceImpl.queryStockAddrByVin(vin);
        callSapInvokVehicleBatchOrderReqVO.setOutAddr(addr);
        callSapInvokVehicleBatchOrderReqVO.setRebateProportion(orderVehicle.getRebateProportion().toString());
        callSapInvokVehicleBatchOrderReqVO.setRebateAccount(orderVehicle.getRebateAccount().toString());
        //特殊折扣固定值 特殊折扣 Guan
        //
        //callSapInvokVehicleBatchOrderReqVO.setDiscountProportion();
//        callSapInvokVehicleBatchOrderReqVO.setSpecialDiscountProportion();
        getDiscountByBase(orderVehicle, callSapInvokVehicleBatchOrderReqVO);
        //
        //合格证邮寄指示符
//       callSapInvokVehicleBatchOrderReqVO.setCertfflag();
        //资金检查指示符
        if ("1".equals(orderVehicle.getType())) {
            callSapInvokVehicleBatchOrderReqVO.setCashcheck("Y");
        } else if ("2".equals(orderVehicle.getType())) {
            callSapInvokVehicleBatchOrderReqVO.setCashcheck("N");
        } else if ("3".equals(orderVehicle.getType())) {
            //
            //表示直销
        }

        callSapInvokVehicleBatchOrderReqVO.setIndicator(DMSEnumsEntity.OperateType.INSERT.getKey());

        //
        //调用资金业务接口，获取特殊折扣
        callSapInvokVehicleBatchOrder(callSapInvokVehicleBatchOrderReqVO);

    }

    private void getDiscountByBase(OrderVehicle orderVehicle, CallSapInvokVehicleBatchOrderReqVO callSapInvokVehicleBatchOrderReqVO) {
        VehiclePriceReqVO vprv = new VehiclePriceReqVO();
        vprv.setProductCode(orderVehicle.getCatalogCode());
        vprv = stoSVehiclePriceDubboServiceImpl.getDiscount(vprv);
        if(vprv!=null){
            if(vprv.getUnitType()==0){
                callSapInvokVehicleBatchOrderReqVO.setSpecialDiscountProportion(vprv.getAmount()+"");
            }else{
                callSapInvokVehicleBatchOrderReqVO.setDiscountProportion(vprv.getAmount()+"");
            }
        }
    }

    /**
     * 配车成功后，调用整车批售订单接口
     */
    private void callSapInvokVehicleBatchOrder(CallSapInvokVehicleBatchOrderReqVO vo) {
        VehicleBatchOrderVO vehicleBatchOrderVO = dozerMapper.map(vo, VehicleBatchOrderVO.class);

        try {
            ApiResult sapResult = sapDubboServiceImpl.sendVehicleBatchOrderToSap(vehicleBatchOrderVO);
            if (200 != sapResult.getCode()) {
                logger.error("SAP接口调用，渠道商资金账户获取失败");
                return;
            }

            JSONObject json = JSONObject.parseObject((String) sapResult.getData());

            OrderVehicle orderVehicle = new OrderVehicle();
            orderVehicle.setOrderCarId((String) json.get("bstkd"));
            orderVehicle.setSapOrderNo((String) json.get("vbeln"));
            orderVehicle.setSapHandleDate((String) json.get("zdate"));
            orderVehicle.setSapHandleTime((String) json.get("ztime"));
            orderVehicle.setSapHandleStatus((String) json.get("zstat"));
            orderVehicle.setSapHandleMessage((String) json.get("zmess"));
            boolean isSuccess = orderVehicleServiceImpl.updateById(orderVehicle);

            if (!isSuccess) {
                logger.error("SAP接口调用，整车批售订单接口,保存SAP返回值失败");
                throw new RuntimeException("SAP接口调用，整车批售订单接口，事务回滚!");
            }

        } catch (Exception ex) {
            logger.error("SAP接口调用，整车批售订单接口，事务回滚!{}",ex);
            throw new RuntimeException("SAP接口调用，整车批售订单接口，事务回滚!");
        }
    }

    /**
     * 审核数据查询
     * @param vo
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    @Transactional
    @LcnTransaction
    public PageInfo<VehicleReturCheckQueryRespVO> queryByList(VehicleReturCheckQueryReqVO vo, int pageNum, int pageSize){
        QueryWrapper qw = new QueryWrapper();
        qw.eq("USER_CODE",vo.getUserCode());
        BaseApplyLevel baseApplyLevel = baseApplyLevelServiceImpl.getOne(qw);

        if(baseApplyLevel == null){
            logger.info("请配置当前用的的审核级别！");
            throw new RuntimeException("请配置当前用的的审核级别！");
        }
        vo.setCurrentLevel(baseApplyLevel.getCurrentLevel());
        return vehicleReturApplyServiceImpl.findListByVO2(vo,pageNum,pageSize);
    }

    /**
     * 整车退车出库数据查询
     * @param vo
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    @Transactional
    @LcnTransaction
    public PageInfo<VehicleReturOutRespVO> queryVehicleReturOut(VehicleReturOutReqVO vo, int pageNum, int pageSize) {
        return vehicleReturApplyServiceImpl.findListByVO3(vo,pageNum,pageSize);
    }

    /**
     * 渠道商退车出库(点击出库)
     * @param vo
     * @return
     */
    @Override
    @Transactional
    @LcnTransaction
    public boolean outbound(VehicleReturOutboundReqVO vo) {

        QueryWrapper qw = new QueryWrapper();
        qw.eq("ORDER_CAR_ID",vo.getOrderCarId());
        PartnerStockOut partnerStockOut =  partnerStockOutServiceImpl.getOne(qw);
        if(partnerStockOut == null){
            partnerStockOut = new PartnerStockOut();
        }

        partnerStockOut.setCreateBy(vo.getUserCode());
        partnerStockOut.setOrderCarId(vo.getOrderCarId());
        partnerStockOut.setOutboundDate(vo.getCreateDate());
        partnerStockOut.setPartnerCode(vo.getPartnerCode());
        partnerStockOut.setVin(vo.getVin());
        partnerStockOut.setSignStatus(1); //已出库
        partnerStockOutServiceImpl.saveOrUpdate(partnerStockOut);

        return true;

    }

    @Override
    @Transactional
    @LcnTransaction
    public PageInfo<PartnerStockOutRespVO> queryPartnerStockOut(PartnerStockOutReqVO vo, int pageNum, int pageSize){
         return partnerStockOutServiceImpl.queryPartnerStockOut(vo,pageNum,pageSize);
    }

    /**
     * 厂端OEM收车
     * @param vo
     * @return
     */
    @Override
    @Transactional
    @LcnTransaction
    public boolean signIn(PartnerStockOutSignInReqVO vo){
        try {
            StoStockInPlanVO stoStockInPlan = new StoStockInPlanVO();
            stoStockInPlan.setVin(vo.getVin());
            stoStockInPlan.setCreateBy(vo.getUserCode());
            stoStockInPlan.setStockInType("3");//退车入库
            stoStockInPlan.setBillCreateTime(new Date());
            stoStockInPlanService.saveAndUpdate(stoStockInPlan);

            QueryWrapper qwUpdateByVin = new QueryWrapper();
            qwUpdateByVin.eq("VIN",vo.getVin());

            PartnerStockOut partnerStockOut = new PartnerStockOut();
            partnerStockOut.setSignStatus(2); //已签收
            partnerStockOutServiceImpl.update(partnerStockOut,qwUpdateByVin);
        }catch (Exception e) {
            logger.info("{}",e);
            throw new RuntimeException("",e);
        }
        return true;
    }

    @Override
    @Transactional
    @LcnTransaction
    public PageInfo<VehicleReturStockInRespVO> queryVehicleReturStockIn(VehicleReturStockInReqVO vo) {
        return null;
    }
}
